package com.lh.ssm.service.impl;

import com.lh.ssm.domain.Cart;
import com.lh.ssm.domain.Order;
import com.lh.ssm.domain.OrderItem;
import com.lh.ssm.mapper.CartMapper;
import com.lh.ssm.mapper.OrderMapper;
import com.lh.ssm.service.OrderService;
import com.lh.ssm.util.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartMapper cartMapper;

    @Override
    public List<Order> findOrdersByUid(int uid) {
        return orderMapper.selectOrdersByUid(uid);
    }

    @Override
    public void createOrder(String uid, String sum, String aid) {
        Order order = new Order();
        String orderId = RandomUtils.getOrderCode();
        order.setId(orderId);
        order.setUid(Integer.parseInt(uid));
        order.setAid(Integer.parseInt(aid));
        order.setTime(new Date());
        order.setTotal(new BigDecimal(sum));
        //默认是未支付状态.
        order.setState(0);

        //插入到shop_order表
        orderMapper.insertOrder(order);

        //插入shop_item表
        List<Cart> carts = cartMapper.selectCartByUid(Integer.parseInt(uid));

        //订单项里的内容,就是购物车里的商品内容
        //List<OrderItem> items = new ArrayList<>();
        for (Cart cart : carts) {
            OrderItem item = new OrderItem();
            item.setOid(orderId);
            item.setPid(cart.getPid());
            item.setCount(cart.getCount());
            item.setTotal(cart.getTotal());
            //items.add(item);
            orderMapper.insertItems(item);
        }



        //清空购物车
        cartMapper.deleteByUid(Integer.parseInt(uid));


    }

    @Override
    public Order findOrderById(String oid) {
        //根据订单id查询到订单信息
        Order order = orderMapper.findOrderById(oid);

        //查询某个订单所关联的所有的订单项
        List<OrderItem> items = orderMapper.findOrderItemsById(oid);
        System.out.println(1);
        for (OrderItem item : items) {
            System.out.println(item==null);
        }
        System.out.println(1);
        order.setItems(items);

        return order;
    }

    @Override
    public void updatePayStateById(String oid) {
        orderMapper.updateOrderById(oid);
    }
}
